import React, { useEffect, useRef, useState } from "react";
import SearchBar from './SearchBar';
import {
  Dimensions,
  Image, NativeModules,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  TouchableOpacity,
  View,
} from "react-native";
import PlayListItem from "../PlayListItem/PlayListItem";
import LinearGradient from "react-native-linear-gradient";
import { Text } from "@rneui/base";
import ImageColors from 'react-native-image-colors'
import Colors from '../../util/Colors'
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Top3Card from "./Top3Card";
import Foundation from "react-native-vector-icons/Foundation";
import {
  top_play_list_163,
  get163PlayListDetail,
  get163SongsBySinger,
  get163Catlist, get163CatPlayList, get163TopList,
} from "../../request/neteaseRequest";
import {top_play_list_KG} from "../../request/kugouRequest";
import { getMgAlbumBySinger, top_play_list_MG } from "../../request/miguRequest";
import _ from 'lodash';
import { getQAlbumDetail, getQPlayMusic, getQSongsBySinger } from "../../request/QQRequest";
import { getKwSongsBySinger } from "../../request/kuwoRequest";
import AntDesign from "react-native-vector-icons/AntDesign";
function getRandomArrayElements(arr, count) {
  return _.slice(_.shuffle(arr),0,count);
}
export default function(props){
  const [search, setSearch] = useState("");
  const [backHeight, setBackHeight] = useState(10000);
  const [imgMainColors, setImgMainColors] = useState(['rgba(7, 45, 64, 0)', '#072C3E', '#072C3E']);

  const [items, setItems] = useState([]);
  const [img, setImg] = useState('');

  const updateSearch = (search) => {
    setSearch(search);
  };
  const scrollPlayList = useRef();
  const mainImg = useRef();

  const pressPlayList = (item) => {
    //console.log(item);
    props.navigation.navigate('ListDetail',{item:item})
  }
  useEffect( () => {
    getMainColores()
    if(items.length === 0)
      initDataHomePage();

  },[img])
  let [neteaseListData,setNeteaseListData] = useState([]);
  let [kgListData,setKgListData] = useState([]);
  let [mgListData,setMgListData] = useState([]);
  let [bsRank,setBsRank] = useState([]);
  let [rgRank,setRgRank] = useState([]);
  let [ycRank,setYcRank] = useState([]);
  async function initDataHomePage(){
    let promise = Promise.all([

      top_play_list_163((r) => {
        neteaseListData = r;
        setNeteaseListData(r);
      }),
      top_play_list_MG((r) => {
        mgListData = r;
        setMgListData(r);
      }),
      top_play_list_KG((r) => {
        kgListData = r;
        setKgListData(r);
      })
    ])
    await promise.then(() => {
      resetList();
    })
    await Promise.all([
      get163PlayListDetail('19723756',(r) => {
        let result = _.slice(r.list,0,3);
        bsRank = result;
        setBsRank(result);
    }),
    get163PlayListDetail('3778678',(r) => {
      let result = _.slice(r.list,0,3);
      rgRank = result;
      setRgRank(result);
    }),
    get163PlayListDetail('2884035',(r) => {
      let result = _.slice(r.list,0,3);
      ycRank = result;
      setYcRank(result);
    })
    ])
    //console.log('##',bsRank,rgRank,ycRank);

  }
  function login(){
    props.navigation.navigate('LoginPage')

  }
  function resetList(){
    let list = [];
    list = _.concat(_.concat(getRandomArrayElements(neteaseListData,8),getRandomArrayElements(mgListData,8)),getRandomArrayElements(kgListData,8))
    setItems(list);
    setImg(list[0].img);
  }
  const getMainColores = async () => {
    const result = await ImageColors.getColors(img, {
      fallback: 'rgba(255,255,255,0.25)',
      cache: true,
      key: img,
    })
    let cs = [];
    switch (result.platform) {
      case 'android':
      case 'web':
        cs.push(Colors.hexToRGBA(result.lightVibrant,0.1));
        cs.push(Colors.hexToRGBA(result.vibrant,0.5));
        cs.push(Colors.hexToRGBA(result.darkVibrant,0.8));
        break
      case 'ios':
        cs.push(Colors.hexToRGBA(result.primary,0.1));
        cs.push(Colors.hexToRGBA(result.secondary,0.5));
        cs.push(Colors.hexToRGBA(result.background,0.8));
        break
      default:
        throw new Error('Unexpected platform key')
    }
    setImgMainColors(cs);
  }
  /**
   * nativeEvent: {
   *     contentInset: {bottom, left, right, top},
   *     contentOffset: {x, y},
   *     contentSize: {height, width},
   *     layoutMeasurement: {height, width},
   *     zoomScale
   *   }
   * @param event
   */
  const changeMainImg = (event) => {
    let x = event.nativeEvent.contentOffset.x;
    let index = Math.round(x / itemWidth);
    if(index >= items.length)
      index = items.length-1;

    let newImg = items[index].img;

    if(newImg !== img){
      setImg(newImg);
    }

  }
  const reNew = () => {
    resetList();
    scrollPlayList.current.scrollTo({x: 30, y: 0, animated: true})
  }
  const pressAlllist = () => {
    props.navigation.navigate('AllPlayList',{kind:'ALL_LIST'})
  }
  const pressAllRank = () => {
    props.navigation.navigate('AllPlayList',{kind:'RANK'})
  }
  const toTopList = (id) => {
    props.navigation.navigate('ListDetail',{item:{id:id,from:'163'}});
  }
  return(
    <View>

      <StatusBar
        backgroundColor="rgba(7, 45, 64, 0.5)"
        hidden={false}
        barStyle="light-content"
      />

      <ScrollView
        showsVerticalScrollIndicator={false}
        style={{marginBottom:55}}
      >
        <TouchableOpacity style={styles.more} onPress={login}>
          <AntDesign name={'login'} size={30} color={Colors.colorPrimary} />
        </TouchableOpacity>
        <SearchBar
          style={styles.searchBar}
          height={searchBarHeight}
          focus={false}
          enable={false}
          onPress={() => props.navigation.navigate('SearchPage')}
        />
        <Image
          style={styles.headerImg}
          source={{uri:img}}
          ref={mainImg}
        />

        <LinearGradient
          locations={[0.1,0.6,1]}
          colors={imgMainColors}
          style={styles.linearGradient}>

        </LinearGradient>
        <View

          style={{
            position:'absolute',
            backgroundColor:imgMainColors[2],
            marginTop:height,
            height:backHeight,
            width: width,
          }}>

        </View>
        <View style={styles.albumContainer}>

          <Text style={styles.homeSideTitle}>歌 单 推 荐</Text>
          <TouchableOpacity style={styles.homeSubTitle} onPress={pressAlllist}>
            <Text style={styles.homeSubTitleText}> 更多</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={reNew}>
            <FontAwesome name={'refresh'} style={styles.freshIcon} size={20}/>
          </TouchableOpacity>
          <ScrollView
            horizontal={true}
            showsHorizontalScrollIndicator={true}
            style={styles.playList}
            ref={scrollPlayList}
            onLayout={() => {
              scrollPlayList.current.scrollTo({x: 30, y: 0, animated: true})
            }}
            onMomentumScrollEnd={changeMainImg}
          >
            {items.map((r) => {
              return(
              <PlayListItem item={r} onPress={()=>pressPlayList(r)}/>
              )
            })}

          </ScrollView>




          <Text style={styles.homeSideTitle}>排 行 榜</Text>

          <TouchableOpacity onPress={pressAllRank}>
            <Foundation name={'indent-more'} style={styles.freshIcon} size={20}/>
          </TouchableOpacity>
          <Top3Card
            img={'https://p1.music.126.net/pcYHpMkdC69VVvWiynNklA==/109951166952713766.jpg'}
            top3={bsRank}
            onPress={() => toTopList('19723756')}
          />
          <Top3Card
            img={'https://p1.music.126.net/ZyUjc7K_GDpD8MO1-GQkmA==/109951166952706664.jpg'}
            top3={rgRank}
            onPress={() => toTopList('3778678')}
          />
          <Top3Card
            img={'https://p1.music.126.net/iFZ_nw2V86IFk90dc50kdQ==/109951166961388699.jpg'}
            top3={ycRank}
            onPress={() => toTopList('2884035')}
          />



        </View>
      </ScrollView>


    </View>
  )


}
const screen = Dimensions.get('window');
const width = screen.width;
const height = screen.height;
const searchBarPaddingVertical = 10;
const swiperHeight = (screen.width * 52) / 90;
const searchBarHeight = 36;
const searchBarPaddingHorizal = 36;
const searchBarBgHeight =
  StatusBar.currentHeight + searchBarHeight + searchBarPaddingVertical * 2;
const swiperOffset = swiperHeight - searchBarBgHeight;
const headerImg = 400;
const itemWidth = (screen.width - 10 * 3) / 2;
const styles = StyleSheet.create({
  searchBar: {
    width: screen.width - searchBarPaddingHorizal * 2,
    height: searchBarHeight,
    position: 'absolute',
    top: StatusBar.currentHeight,
    marginHorizontal: searchBarPaddingHorizal,
    zIndex:90
  },

  headerImg:{
    height:400,
    width:width,
    zIndex: 0,
  },

  linearGradient: {
    marginTop:-400,
    height:height,
    width: width,
    zIndex: 10,
    flex: 1,

  },

  homeSideTitle: {
    fontFamily:'Raleway-Bold',
    fontSize: 16,
    color: '#fff',
    paddingTop: 20,
    paddingBottom: 20,
    marginLeft: 10,

  },
  homeSubTitle: {
    fontFamily:'Raleway-Bold',
    fontSize: 14,
    color: 'rgba(255,255,255,0.59)',
    position:'relative',
    textDecorationLine:'underline',
    top:-39,
    left:88

  },
  homeSubTitleText: {
    fontFamily:'Raleway-Bold',
    fontSize: 14,
    color: 'rgba(255,255,255,0.59)',
    textDecorationLine:'underline',
  },
  freshIcon: {
    color: '#fff',
    marginTop: -30,

    position:'relative',
    left:width-30
  },
  playList:{
    marginLeft:20
  },
  albumContainer: {
    marginTop: -450,
    zIndex:90,
  },
  more:{
    position:'absolute',
    left:0,
    top:StatusBar.currentHeight,

    zIndex:999999
  }

});
